package com.eirikb.server;

import com.eirikb.shared.Service;
import com.eirikb.shared.events.Event;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author eirikb
 */
public class Server extends RemoteServiceServlet implements Service {

    private Hashtable<String, ServerUser> users;
    private final int PINGRATE = 20;

    public Server() {
        users = new Hashtable<String, ServerUser>();
        ping();
    }

    public Boolean login(String nick, String name) {
        System.out.println("Login");
        ServerUser serverUser = new ServerUser(this, nick, name);
        users.put(nick, serverUser);
        return serverUser.connect();
    }

    public Event[] checkUpdates(String nick) {
        System.out.println("Check updates");
        ServerUser serverUser;
        if ((serverUser = users.get(nick)) == null) {
            System.out.println("Fannt ikke bruker");
            return null;
        } else {
            Event[] all = serverUser.getEvents();
            System.out.println("Fannt bruker.. sender events: " + all.length);
            for (Event e : all) {
                System.out.println(e);
            }
            serverUser.ping();
            return all;
        }
    }

    public void sendMessage(String nick, String msg) {
        System.out.println("Send message");
        ServerUser serverUser;
        if ((serverUser = users.get(nick)) == null) {
            System.out.println("Fannt ikke bruker");
        } else {
            System.out.println("Fannt bruker.. sender medling");
            serverUser.sendMessage(msg);
        }
    }

    public Boolean changeNick(String nick, String newNick) {
        if (users.get(newNick) == null) {
            users.get(nick).changeNick(newNick);
            users.put(newNick, users.get(nick));
            users.remove(nick);
            return true;
        } else {
            return false;
        }
    }

    private void ping() {
        new Thread() {

            public void run() {
                while (true) {
                    String[] nicks = users.keySet().toArray(new String[users.keySet().size()]);
                    for (String nick : nicks) {
                        ServerUser serverUser = users.get(nick);
                        if (!serverUser.getPing()) {
                            System.out.println("Remove " + nick);
                            users.get(nick).disconnect();
                            users.remove(nick);
                        }
                    }
                    try {
                        Thread.sleep(PINGRATE * 1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }.start();
    }
}
